import {
  OrderStatus
} from '../config';
import {
  fetchOrders,
  fetchOrdersCount,
} from '../../../services/order/orderList';
import {
  pay
} from '../../../tools/pay'
import {
  ui
} from '../../../tools/ui';
import {
  ds
} from '../../../tools/data';
import {
  checkTool
} from '../../../tools/check';
import {
  exTool
} from '../../../pages/usercenter/exTicket/exTool';
import {
  msg
} from '../../../tools/msg';
import {
  dsx
} from '../../../tools/datax';
import {
  dateTool
} from '../../../tools/date';
import {
  orderTabs,
  ticketTabs,
  deliveryTabs
} from './tabs';
import {
  nav2
} from '../../../tools/nav2'
import {
  shops
} from '~/tools/shops';
import {
  coupon
} from '~/tools/coupon';
import {
  users
} from '~/tools/users'
import {
  orderTool
} from '~/tools/oderTool'
Page({
  page: {
    size: 5,
    num: 1,
  },
  data: {
    action: 'myOrder', // or 'manage'
    user: {},
    tabs: [],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: -1,
    ticket: false,
    search: {},
    startY: 0,
    ctrlBarFolded: true,
    dateRange: {
      start: 0,
      end: 0
    },
    selShop: {
      name: '所有门店',
      value: 'all'
    },
  },
  onLoad(query) { // { action: 'myOrder' | 'manage', ticket: true | 'undefined', search: {orderId, openId, refound, ticket, goodsId, dateRange} }
    // console.log(query)
    query = this.parseTicket(query)
    this.initTitle(query)
    this.initSearch(query)
    this.initDateRange()
    this.startCountDownTimer()

    let status = parseInt(query.status)
    this.initUser(query, user => {
      this.initTabs(query)
      if (status != -1) {
        status = this.data.tabs.map((t) => t.key).includes(status) ? status : -1;
      }
      this.init(status);
      this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
    })
  },
  startCountDownTimer() {
    const that = this
    const updateCountDown = function () {
      const {
        orderList
      } = that.data
      const list = orderList || []
      list.forEach(order => {
        if (order.payStatus != 'success') return
        if (!order.goodsSnap[0].fastDelivery) return
        const endTime = order.updateTime + 39 * 60 * 1000,
          now = Date.now()
        order.countDown = dateTool.format(endTime - now, 'mm:ss')
        order.deliveryTimeout = (now > endTime)
      })

      that.setData({
        orderList,
        timer: setTimeout(updateCountDown, 1000)
      })
    }
    this.setData({
      timer: setTimeout(updateCountDown, 1000)
    })
  },
  onUnload() {
    clearTimeout(this.data.timer)
  },
  onHide() {
    clearTimeout(this.data.timer)
  },
  selShopTap() {
    const {
      selShop
    } = this.data
    if (!selShop.options) this.initSelShop()
    const that = this
    ui.actionSheetx(selShop.options, (kv) => {
      that.setData({
        'selShop.name': kv.name,
        'selShop.value': kv.value
      })

      that.setData({
        'search.shopId': selShop.value,
        status: -1,
        curTab: -1
      })
      that.refreshList()
    })
  },
  initSelShop() {
    const {
      selShop
    } = this.data
    if (!selShop.options) {
      selShop.options = []
      selShop.options.push({
        name: selShop.name,
        value: selShop.value
      });
      const options = selShop.options
      const slist = shops.getShopList()
      // console.log(slist)
      for (const s of slist) {
        options.push({
          value: String(s.id),
          name: s.name
        })
      }
    } else {
      // console.log(selShop)
      selShop.name = selShop.options[0].name;
      selShop.value = selShop.options[0].value;
    }
    this.setData({
      selShop
    })
    // console.log(selShop)
  },
  initDateRange() {
    const search = this.data.search
    let dateRange = this.data.dateRange;
    if (search.dateRange) dateRange = search.dateRange
    else {
      const now = new Date(),
        dayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
      dateRange.start = dayStart;
      dateRange.end = dayStart + 3600 * 24 * 1000 - 1;
    }
    this.setData({
      dateRange
    })
    this.updateDateRange()
  },
  updateDateRange() {
    const {
      start,
      end
    } = this.data.dateRange
    const dpStart = this.selectComponent("#dpstart"),
      dpEnd = this.selectComponent("#dpend");
    dpStart.initTimestamp(start)
    dpEnd.initTimestamp(end)
  },
  onPickStartDate(e) {
    const {
      timestamp
    } = e.detail;
    // console.log(new Date(timestamp))
    this.setData({
      dateRange: {
        start: timestamp,
        end: this.data.dateRange.end
      }
    })
    this.justifyDateRange()
  },
  justifyDateRange() {
    let {
      start,
      end
    } = this.data.dateRange

    this.setData({
      curDateRangeIndex: -1
    })
    if (start > end) {
      end = start;
      this.setData({
        dateRange: {
          start,
          end
        }
      })
      this.updateDateRange();
    }
    this.setData({
      'search.dateRange': {
        start,
        end
      }
    })
  },
  onPickEndDate(e) {
    const {
      timestamp
    } = e.detail;
    this.setData({
      dateRange: {
        start: this.data.dateRange.start,
        end: timestamp + 3600 * 24 * 1000 - 1
      }
    })
    this.justifyDateRange()
  },
  parseTicket(query) {
    if (!query.ticket) query.ticket = false
    query.ticket = (query.ticket == 'undefined' ? false : JSON.parse(query.ticket))
    return query
  },
  initSearch(query) {
    const {
      search
    } = query
    if (search) this.setData({
      search: JSON.parse(search)
    })
    // console.log(this.data.search)
  },
  initTabs(query) {
    const ticket = query.ticket
    const user = this.data.user
    let tabs = orderTabs
    if (ticket) tabs = ticketTabs
    else if (this.data.action == 'manage' && user.role == 'delivery') tabs = deliveryTabs

    this.setData({
      tabs,
      ticket
    })
  },
  initTitle(query) {
    const {
      ticket,
      action
    } = query
    if (action) {
      this.setData({
        action
      })
    }
    let title = '订单管理'
    if (this.data.action == 'myOrder') {
      title = (ticket ? '我的水票' : '我的订单')
    }
    wx.setNavigationBarTitle({
      title
    })
    this.setData({
      title
    })
  },
  initUser(query, cb) {
    ds.cloudGetByOpenid('users', res => {
      // console.log(res)
      const user = res.result.data[0]
      if (!user.role) user.role = 'custom'
      this.setData({
        user
      })
      cb(user)
    })
  },
  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },
  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.getOrderList(this.data.curTab);
    }
  },
  onPageScroll(detail) {
    return
    wx.pageScrollTo({
      scrollTop: detail.scrollTop - 10,
      duration: 100,
      success: () => {
        // this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
      }
    });
  },
  onPullDownRefresh(e) {
    return
    const {
      callback
    } = e.detail || {};
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false
        });
        callback && callback();
      })
      .catch((err) => {
        this.setData({
          pullDownRefreshing: false
        });
        Promise.reject(err);
      });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },
  // 立即支付
  onPayTap(e) {
    const order = e.target.dataset.order
    // console.log(order)
    const {
      id
    } = order

    pay.payOrder({
      id
    }, res => {
      // console.log(res)
      this.onRefresh()
    })

  },
  // 线下支付
  onPayOffline(e) {
    const order = e.target.dataset.order
    const {
      id
    } = order
    ui.confirm('确定线下支付吗？', res => {
      if (!res) return
      ds.cloudUpdate('orders', id, {
        payOffline: true,
        status: '待配送',
        updateTime: new Date().getTime()
      }, res => {
        msg.notifyDelivery(id)
        this.refreshList(this.data.curTab)
      })
    })
  },
  async onCancelExchangeTap(e) { // 撤销兑换
    if (!await ui.confirmx('撤销兑换吗？')) return
    const order = ui.eventData(e, 'order')
    ui.loading()
    exTool.cancelTicketOrder(order).then(res => {
      this.refreshList(this.data.status)
      ui.loading(false)
      ui.toast(res.result == 'success')
    })
  },
  // 申请退款
  onRefoundTap(e) {
    const order = e.currentTarget.dataset.order
    let {
      totalFee
    } = order

    ui.text('输入退款金额', `最多${totalFee.toFixed(2)}`, (confirm, txt) => {
      if (!confirm) return
      const inputNum = txt * 1
      const fields = [{
        value: txt,
        fn: txt => new RegExp("^" + checkTool.CommonRegex.decimal + "$").test(txt) && inputNum <= totalFee * 1 && inputNum > 0,
        title: '输入金额'
      }]
      if (!checkTool.check(fields)) return
      this.doRefound(order, inputNum)
    })
  },
  // 取消退款
  onCancelRefoundTap(e) {
    const order = e.currentTarget.dataset.order
    ui.confirm('确定取消吗？', confirm => {
      if (!confirm) return
      ui.loading()
      ds.coll('orders')
        .where({
          _id: order._id
        })
        .update({
          data: {
            refoundInfo: ds.cmd.remove()
          }
        })
        .then(res => {
          ui.loading(false)
          this.refreshList(this.data.status)
        })
    })
  },
  doRefound(order, refoundFee) {
    ui.loading()
    ds.cloudUpdate('orders', order._id, {
      refoundInfo: {
        fee: refoundFee,
        updateTime: new Date().getTime(),
        status: 'wait'
      }
    }, async res => {
      const success = res.result?.errMsg.endsWith(":ok")
      if (!success) return ui.loading(false)

      // 通知管理员
      const userRes = await ds.coll('users')
        .where({
          role: 'admin'
        })
        .get()
      const users = userRes.data
      users.forEach(async adminUser => {
        await this.sendMsg(adminUser, refoundFee, order)
        await this.sendSms(adminUser, order)
      })
      ui.loading(false)
      this.refreshList(this.data.status)
    })
  },
  async sendMsg(adminUser, refoundFee, order) { // 微信服务通知
    const datetime = new Date().getTime()
    const search = JSON.stringify({
      orderId: order._id
    })
    if (order.ticketInfo) search.ticket = true
    try {
      await msg.push({
        touser: adminUser._openid, // openid of user
        page: `/pages/order/order-list/index?action=manage&search=${search}`,
        amount: refoundFee + '',
        title: '订单退款申请',
        remark: '',
        datetime: datetime + '',
        addr: ''
      }).then(res => {
        // console.log(res)
      })
    } catch (err) {
      console.error(err)
    }
  },
  async sendSms(adminUser, order) { // 短信
    const datetime = new Date().getTime()
    try {
      await wx.cloud.callFunction({
        name: 'sendSmsTc',
        data: {
          templateName: "refound_apply",
          templateParamList: [dateTool.format(datetime, 'M月d日hh点'), "1", '用户' + this.data.user.phoneNumber + '的订单' + order._id],
          phoneNumberList: ["+86" + adminUser.phoneNumber],
          sessionContext: 'order refund apply'
        }
      }).then(res => {
        // console.log(res, adminUser.phoneNumber)
      })
    } catch (err) {
      console.error(err)
    }
  },
  prefixZero(num) {
    return num < 10 ? '0' + num : num
  },
  async orderStatusTap(e) { // 指派配送员
    const user = this.data.user
    const order = ui.eventData(e, 'order'),
      status = order.status
    if (status != '待配送' || ['admin', 'master'].indexOf(user.role) < 0) return
    if (!await ui.confirmx('指派其他配送员吗？')) return

    ui.loading()
    const deliveryInfo = (await wx.cloud.callFunction({
      name: 'userCmd',
      data: {
        cmd: 'findDeliveryUsers',
        orderId: order._id
      }
    })).result // { addr, deliveryMen, order }
    ui.loading(false)
    // console.log(deliveryInfo)

    const deliveryMen = deliveryInfo.deliveryMen,
      actionSheets = {}
    if (!deliveryMen.length) {
      return ui.toast(false, '该店未指派配送员')
    }
    for (const index in deliveryMen) {
      const man = deliveryMen[index]
      if (man._id == user._id) continue
      actionSheets[index] = man.personInfo?.nickName || man.phoneNumber
    }

    // console.log(actionSheets)
    ui.actionSheet(actionSheets, async (nickName, index) => {
      const man = deliveryMen[index]
      if (!await ui.confirmx(`指派${nickName}配送该订单吗？`)) return
      // console.log(man)
      ui.loading()
      await this.startDelivery(order, false, man)
    })
  },
  onExecOrderTap(e) { // 兑换水票
    const order = e.target.dataset.order
    exTool.useTicket(order)
      .then(async res => {
        // console.log(res)
        const success = res?.result?.errMsg?.endsWith(":ok")
        ui.toast(success)
        if (!success) return

        const yes = await ui.confirmx('兑换成功，是否返回？')
        if (yes) wx.navigateBack()
        else this.refreshList(this.data.curTab)
      })
      .catch((err, mm) => {
        this.refreshList(this.data.curTab)
        console.error(err, mm)
      })
  },
  async onDeliveryTap(e) { // 立即配送
    const order = e.target.dataset.order
    ui.confirm('确定配送该订单吗？', res => {
      if (!res) return
      this.startDelivery(order)
    })
  },
  onCancelDeliveryTap(e) { // 取消配送
    const order = e.target.dataset.order
    ui.confirm('确定取消配送吗？', res => {
      if (!res) return
      this.startDelivery(order, true)
    })
  },
  onGetPaymentTap(e) { // 已收款
    const order = e.target.dataset.order
    ui.confirm('确定已收款吗？', res => {
      if (!res) return
      ds.cloudUpdateWhere('orders', {
        _id: order.id
      }, {
        payStatus: 'success'
      }, res => {
        this.refreshList(this.data.curTab)
      })
    })
  },
  onCompleteOrderTap(e) { // 送达
    const {
      user
    } = this.data
    const order = e.target.dataset.order
    this.lastCompleteOrder = order
    const num = orderTool.totalGoodsNum(order)
    // console.log(order)
    wx.navigateTo({
      url: `/pages/showqr/showqr?title=空桶押金&userOpenId=${order._openid}&nickName=${user.personInfo?.nickName}&add=${num}&callBeforeCompleteOrder=true`,
    })
    // this.doCompleteOrder(order)
  },
  doCompleteOrder(order) {
    ui.confirm('确定完成该订单吗？', res => {
      if (!res) return
      ui.loading()
      ds.cloudUpdateWhere('orders', {
        _id: order.id,
        payStatus: 'success'
      }, {
        status: '已送达',
        completeTime: Date.now()
      }, res => {
        // console.log(res)
        const success = res.result.errMsg?.endsWith(":ok")
        if (success) {
          this.giveFastDeliveryTimeoutCoupon(order)
          const status = OrderStatus.COMPLETE
          this.setData({
            status
          })
          this.refreshList(status)
        } else {
          ui.toast(success)
          console.error(res)
        }
        ui.loading(false)
      })
    })
  },
  async giveFastDeliveryTimeoutCoupon(order) {
    if (!order.goodsSnap[0].fastDelivery) return
    const level = this.timeoutLevel(order.completeTime, order.updateTime)
    if (level == 0) return

    const values = [
      [],
      [5, 5],
      [5, 10],
      [10, 15]
    ]
    const validDays = [
      [],
      [15, 30],
      [15, 30],
      [15, 30]
    ]
    try {
      const user = await users.getUserByOpenid(order._openid, {
        _id: 1,
        "personInfo.nickName": 1
      })
      const valueList = values[level],
        validDaysList = validDays[level]
      const coupons = valueList.map((value, index) => {
        return this.makeCoupon(order, user, validDaysList[index], value)
      })
      let num = 0
      for (const c of coupons) {
        const res = await dsx.cloudUpdate('coupons', null, c)
        if (res.result.errMsg.endsWith(":ok")) num += 1
      }
      if (num < 2) console.error('部分超时券发放失败')
    } catch (err) {
      console.error(err)
    }
  },
  makeCoupon(order, user, validDuration, value) {
    return {
      amount: 1,
      left: 1,
      limit: 1,
      start: order.completeTime,
      end: order.completeTime + validDuration * 24 * 3600 * 1000,
      unit: value,
      minus: value,
      orderId: order._id,
      title: `急送超时赔付${value}元券`,
      userId: user._id,
      userName: user.personInfo.nickName || '(昵称未设置)',
    }
  },
  timeoutLevel(completeTime, updateTime) {
    const timeDiff = (completeTime - updateTime) / 1000 / 60 - 39
    if (timeDiff <= 0) return 0
    if (timeDiff > 0 && timeDiff < 10) return 1
    if (timeDiff >= 10 && timeDiff < 25) return 2
    if (timeDiff >= 25) return 3
  },
  updateBarrelInfoCallback() {
    const order = this.lastCompleteOrder
    // console.log('xxx', order)

    wx.nextTick(() => {
      this.doCompleteOrder(order)
    })

  },
  // 加收步梯费
  onAddStepFeeTap(e) {
    const {
      user
    } = this.data
    const order = e.target.dataset.order
    ui.confirm("加收步梯费吗？", res => {
      if (!res) return

      wx.navigateTo({
        url: `/pages/showqr/showqr?title=步梯费&orderId=${order.id}`,
      })
    })
  },
  // 收桶押金
  onAddPladgeTap(e) {
    const {
      user
    } = this.data
    const order = e.target.dataset.order
    ui.confirm("加收桶押金吗？", res => {
      if (!res) return

      wx.navigateTo({
        url: `/pages/showqr/showqr?title=空桶押金&userOpenId=${order._openid}&nickName=${user.personInfo?.nickName}`,
      })
    })
  },
  async startDelivery(order, cancel = false, deliveryMan) {
    const orderId = order.id || order._id
    const user = deliveryMan || this.data.user
    // console.log(user._openid, orderId, cancel)
    let result = null
    await wx.cloud.callFunction({
        name: 'startDelivery',
        data: {
          deliveryMan: user._openid,
          orderId,
          cancel
        }
      })
      .then(async res => {
        result = res
        const status = (cancel ? OrderStatus.PENDING_DELIVERY : OrderStatus.DELIVERY)
        // console.log(res)
        this.setData({
          status
        })
        this.refreshList(status)
        if (deliveryMan) await msg.notifyDeliveryMan(order._id, deliveryMan._id)
        ui.loading(false)
      })

    return result
  },
  getPayStatus(order) {
    if (order.payStatus == 'success') {
      return order.status || '待配送'
    }
    return '待付款'
  },
  // 获取订单数据
  getOrderList(statusCode = -1, reset = false) {
    const {
      ticket,
      action,
      user,
      search,
      dateRange,
      selShop
    } = this.data

    const params = {
      parameter: {
        pageSize: this.page.size,
        pageNum: this.page.num,
        ticket,
        action,
        user,
        search
      },
    };

    if (statusCode !== -1) params.parameter.orderStatus = statusCode;
    this.setData({
      listLoading: 1
    });

    return fetchOrders(params)
      .then((res) => { // res为orders数据
        this.page.num++;
        let orderList = [];
        if (res && res.data) {
          orderList = (res.data || []).map((order) => {
            const res = {
              id: order._id, // order.orderId,
              orderNo: order._id, // order.orderNo,
              parentOrderNo: order.parentOrderNo,
              storeId: order.storeId,
              storeName: order.storeName,
              statusDesc: order.status, // this.getPayStatus(order), // order.orderStatusName,
              amount: order.totalFee, // order.paymentAmount,
              totalAmount: order.totalFee + (Number(order.deductFeeInfo?.fee) || 0), // order.totalAmount,
              logisticsNo: '', // order.logisticsVO.logisticsNo,
              goodsList: (order.goodsList || []).map((goods) => ({
                id: goods.id,
                thumb: goods.thumb, // cosThumb(goods.thumb, 70),
                title: goods.title, // goods.goodsName,
                skuId: goods.skuId,
                spuId: goods.spuId,
                specs: goods.specs,
                price: goods.price, // goods.tagPrice ? goods.tagPrice : goods.actualPrice,
                num: goods.num, // goods.buyQuantity,
                titlePrefixTags: goods.tagText ? [{
                  text: goods.tagText
                }] : [],
              })),
              totalNum: this.totalGoodsNum(order.goodsList),
              buttons: order.buttonVOs || [],
              groupInfoVo: order.groupInfoVo,
              freightFee: order.stepFee || 0,
            } // res

            this.descTips(order)
            OrderStatus.descRefoundStatus(order.refoundInfo)

            Object.keys(order).forEach(key => {
              if (res[key] == undefined) res[key] = order[key]
            })
            res.isCouponValid = coupon.isCouponValid(res)
            return res
          }) // orderList
        }
        return new Promise((resolve) => {
            if (reset) {
              this.setData({
                orderList: []
              }, () => resolve());
            } else resolve();
          })
          .then(() => {
            const loaded = orderList
            orderList = this.data.orderList.concat(orderList)
            this.setData({
              orderList,
              listLoading: loaded.length > 0 ? 0 : 2,
            })
            this.loadAddr(orderList)
          });
      })
      .catch((err) => {
        this.setData({
          listLoading: 2
        });
        return Promise.reject(err);
      });
  },
  totalGoodsNum(goodsList) {
    let num = 0
    for (const goods of goodsList) num += (goods.num || 0)
    return num
  },
  descTips(order) {
    if (order.status == '待配送' || order.status == '配送中')
      order.deliveryTips = dateTool.readable(this.deliveryTips(order.updateTime))
  },
  deliveryTips(timestamp) {
    const workFromHour = 8,
      work2Hour = 20
    const date = new Date(Number(timestamp))
    const hours = date.getHours()
    if (hours < workFromHour)
      date.setHours(workFromHour + 1, 30, 0, 0) // 9:30
    else if (hours >= workFromHour && hours < work2Hour - 1) {
      date.setHours(hours + 1, date.getMinutes() + 30, 0, 0) // 90 mins after
    } else {
      date.setDate(date.getDate() + 1);
      date.setHours(workFromHour + 1, 30, 0, 0);
    }
    return date.getTime()
  },
  async loadAddr(orderList) {
    if (this.data.action != 'manage') return
    for (const order of orderList) {
      if (!order || order.addr) continue
      const addr = (await ds.coll('delivery_addr')
        .where({
          _openid: order._openid
        })
        .get()).data[0]
      order.addr = addr || undefined
      order.shop = shops.getShop(addr.shop)
    }
    this.setData({
      orderList
    })
  },
  mobileTap(e) {
    const mobile = ui.eventData(e, 'mobile')
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
  },
  shopNameTap(e) {
    const {
      user
    } = this.data
    const order = ui.eventData(e, 'order'),
      that = this
    if (!user.role || user.role == 'staff' || user.role == 'custom') return

    if (user.role == 'delivery' || user.role == 'master') {
      if (order.status != '待配送') return ui.toast(false, '非待配送订单')
    }

    console.log(this.data)
    const data = {
      user,
      order
    }
    wx.navigateTo({
      url: `/pages/order/order-list/change-shop/change-shop?data=${JSON.stringify(data)}`,
    })
  },
  shopChanged() {

  },
  onSearchTap(e) {
    ui.text('搜索订单', '输入订单号', (confirm, text) => {
      if (!confirm) return
      this.setData({
        search: {
          orderId: text
        },
        status: -1,
        curTab: -1,
        dateRange: {}
      })
      this.refreshList()
    })
  },
  onTicketExchangeTap() {
    this.setData({
      'search.ticketOrderId': true,
      status: -1,
      curTab: -1
    })
    this.refreshList()
  },
  onTicketTap(e) {
    this.setData({
      'search.ticket': true,
      status: -1,
      curTab: -1
    })
    this.refreshList()
  },
  onRefoundFilterTap() {
    this.setData({
      'search.refound': true,
      status: -1,
      curTab: -1
    })
    this.refreshList()
  },
  onClearTap() {
    this.setData({
      search: {},
      status: -1,
      curTab: -1
    })
    this.initSelShop()
    this.refreshList()
  },
  onSaleStatisTap() {
    nav2.navigate('/pages/order/statistics/sale/sale-statistics');
  },
  onDeliStatisTap() {
    nav2.navigate('/pages/order/statistics/delivery/delivery-statistics');
  },
  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  onTabChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      status: value,
    });
    this.refreshList(value);
  },

  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const {
        tabs
      } = this.data;
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({
        tabs
      });
    });
  },

  refreshList(status = -1) {
    this.page = {
      size: this.page?.size || 2,
      num: 1,
    };
    this.setData({
      curTab: status
    });

    return Promise.all([
      this.getOrderList(status, true),
      this.getOrdersCount(),
    ]);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    const {
      order
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/order-detail/index?orderNo=${order.orderNo}`,
    });
  },
  onFoldCtrlBarTap() {
    this.setData({
      ctrlBarFolded: !this.data.ctrlBarFolded
    })
  },
  onFoldCtrlUpTap() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300 // 动画时长（ms）
    });
  },
  nav2TicketOrderTap(e) {
    const ticketOrderId = ui.eventData(e, 'ticketorderid'),
      action = this.data.action
    nav2.orderList(action, true, JSON.stringify({
      orderId: ticketOrderId
    }))
  }
});